<template>
  <div class="page-miH page-bgBack">
    <a-row type="flex" class="groupHead">
      <a-icon type="left" style="font-size: 16px;cursor:pointer;" @click="$router.go(-1)" />
      <div>编辑分组</div>
      <a-button type="link" icon="plus" @click="createGroup">
        添加分组
      </a-button>
    </a-row>
    <div class="groupTable" v-if="showTable">
      <a-table :data-source="groupList" :loading="tableLoading" :pagination="false">
        <!-- <a-table-column title="排序" align="center">
          eslint-disable-next-line
          <template slot-scope="text">
            <span class="handleDrag"><a-icon type="menu"/></span>
          </template>
        </a-table-column> -->
        <a-table-column title="分组名称" align="center" width="50%">
          <template slot-scope="text"
            ><span>{{ text.name }}</span></template
          >
        </a-table-column>
        <a-table-column title="分组内合同类型数" align="center">
          <template slot-scope="text">{{ text.categoryCount }}</template>
        </a-table-column>
        <a-table-column title="操作" align="center">
          <template slot-scope="text">
            <a-button type="link" :disabled="text.isSystem" @click="updateGroup(text)">编辑</a-button>
            <a-divider type="vertical" />
            <a-button type="link" :disabled="text.isSystem || groupList.length === 1 || text.categoryCount !== 0" @click="deleteGroup(text)"
              >删除</a-button
            >
          </template>
        </a-table-column>
      </a-table>
    </div>
    <a-modal
      :title="theCurrentGroupId ? '编辑分组' : '新增分组'"
      :visible="addGroupVisible"
      :confirm-loading="confirmLoading"
      @ok="confirmAddGroup"
      @cancel="addGroupVisible = false"
    >
      <div>
        <a-form :form="groupForm" :label-col="{ span: 7 }" :wrapper-col="{ span: 12 }">
          <a-form-item :colon="true" label="分组名称">
            <a-input v-decorator="['name', { rules: [{ required: true, message: '请输入' }] }]" />
          </a-form-item>
        </a-form>
      </div>
    </a-modal>
  </div>
</template>

<script>
import Sortable from "sortablejs";
import { getContractGroups, addContractGroups, updateContractGroups, batchDelContractGroups } from "@/api/company/contract";
import { isContainByString } from "@/utils/index";
export default {
  data() {
    return {
      showTable: true,
      addGroupVisible: false,
      confirmLoading: false,
      theCurrentGroupId: "",
      groupForm: this.$form.createForm(this),
      groupList: [],
      tableLoading: false,
      isContainByString
    };
  },
  created() {
    this.getContractGroups();
  },
  mounted() {
    // this.initSortable();
  },
  methods: {
    initSortable() {
      new Sortable(document.querySelector(".ant-table-tbody"), {
        handle: ".handleDrag",
        onEnd: this.onDragEnd
      });
    },
    onDragEnd(evt) {
      const newIndex = evt.newIndex;
      const oldIndex = evt.oldIndex;
      const groupListTemp = [...this.groupList];
      const groupListMap = {};
      const initArr = [];
      for (let i = 0; i < groupListTemp.length; i++) {
        groupListMap[i] = groupListTemp[i];
        initArr.push(i);
      }
      initArr.splice(oldIndex, 1);
      initArr.splice(newIndex, 0, oldIndex);
      const groupListTempNew = initArr.map(idx => groupListMap[idx]);
      this.groupList = groupListTempNew;
      this.showTable = false;
      this.$nextTick(() => {
        this.showTable = true;
        this.$nextTick(() => {
          this.initSortable();
        });
      });
    },
    // 获取分组列表
    getContractGroups() {
      this.tableLoading = true;
      getContractGroups({
        subjectId: this.isContainByString("contractAdmin") ? "0" : this.$store.state.hr.companyId
      }).then(res => {
        this.tableLoading = false;

        for (var i = 0; i < res.data.length; i++) {
          res.data[i].index = i;
        }
        this.groupList = res.data;
      });
    },
    // 新增合同分组
    createGroup() {
      this.theCurrentGroupId = "";
      this.addGroupVisible = true;
      this.groupForm.resetFields();
    },
    // 编辑合同分组
    updateGroup(item) {
      this.theCurrentGroupId = item.id;
      this.addGroupVisible = true;
      setTimeout(() => {
        this.groupForm.setFieldsValue({
          name: item.name
        });
      }, 0);
    },
    // 确定增加合同分组
    confirmAddGroup(e) {
      this.confirmLoading = true;
      this.groupForm.validateFields((err, values) => {
        values.sort = "1";
        values.subjectId = this.isContainByString("contractAdmin") ? "0" : this.$store.state.hr.companyId;
        if (!err) {
          if (!this.theCurrentGroupId) {
            this.postAddContractGroups(values);
          } else {
            this.putUpdateContractGroups({
              ...values,
              id: this.theCurrentGroupId
            });
          }
        }
      });
    },
    async postAddContractGroups(values) {
      try {
        await addContractGroups(values);
        this.$message.success("添加成功");
        this.addGroupVisible = false;
        this.getContractGroups();
        this.confirmLoading = false;
      } catch (err) {
        console.log("error log --> ", err);
        this.confirmLoading = false;
      }
    },
    async putUpdateContractGroups(values) {
      try {
        await updateContractGroups(values);
        this.$message.success("编辑成功");
        this.addGroupVisible = false;
        this.getContractGroups();
        this.confirmLoading = false;
      } catch (err) {
        console.log("error log --> ", err);
        this.confirmLoading = false;
      }
    },
    // 删除合同分组
    deleteGroup(item) {
      this.$confirm({
        title: "提示",
        content: `确定删除分组 ${item.name} 吗？`,
        okText: "确认",
        cancelText: "取消",
        onOk: () => {
          this.delBatchDelContractGroups(item.id);
        }
      });
      this.batchDeleteVisible = true;
      this.theCurrentGroup = item;
    },
    async delBatchDelContractGroups(id) {
      try {
        await batchDelContractGroups([id]);
        this.$message.success("删除成功");
        this.getContractGroups();
      } catch (err) {
        console.log("error log --> ", err);
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.groupHead {
  // position: sticky;
  // top: 0;
  background: #fff;
  width: 100%;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid #e8e8e8;
  padding: 0 24px;
  z-index: 99;
  div {
    font-size: 16px;
    font-weight: 500;
    color: rgba(0, 0, 0, 0.85);
  }
}
.groupTable {
  padding: 24px;
}
.handleDrag {
  cursor: pointer;
}
</style>
